package com.wechat.network;

import com.swak.reactivex.transport.Channel;
import com.swak.reactivex.transport.Message;
import com.wechat.command.Command;

import lombok.Data;

/**
 * 网络 -  通道
 * 
 * @author 618lf
 */
public interface NetworkChannel {

	/**
	 * 获得当前的通道
	 * 
	 * @return
	 */
	Channel getChannel();

	/**
	 * 发送消息
	 * 
	 * @param message
	 */
	default void send(Command message) {
		try {
			getChannel().send(Message.forMessage(message));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// *************** Create Network Channel ************************
	static final String CHANNEL_KEY = NetworkChannel.class.getName() + ".CHANNEL";

	static public NetworkChannel getOrAddChannel(Network network, Channel ch) {
		if (ch == null) {
			return null;
		}
		NetworkChannel ret = (NetworkChannel) ch.getAttribute(CHANNEL_KEY);
		if (ret == null) {
			ret = new NetworkChannelImpl(network, ch);
			if (ch.isConnected()) {
				ch.setAttribute(CHANNEL_KEY, ret);
			}
		}
		return ret;
	}

	static public void removeChannelIfDisconnected(Channel ch) {
		if (ch != null && !ch.isConnected()) {
			ch.removeAttribute(CHANNEL_KEY);
		}
	}

	static public void removeChannel(Channel ch) {
		if (ch != null) {
			ch.removeAttribute(CHANNEL_KEY);
		}
	}

	@Data
	static class NetworkChannelImpl implements NetworkChannel {
		final Network network;
		final Channel channel;

		NetworkChannelImpl(Network network, Channel channel) {
			this.network = network;
			this.channel = channel;
		}
	}
}